// 配置数据
const STORAGE_KEY = 'promptManagerData';
let prompts = [];
let filteredPrompts = [];
let currentEditIndex = null;
let isMinimized = false;
let lastFocusedElement = null;

// 从chrome.storage加载数据
function loadPrompts(callback) {
    chrome.storage.local.get([STORAGE_KEY], function (result) {
        prompts = result[STORAGE_KEY] || [];
        filteredPrompts = [...prompts];
        if (callback) callback();
    });
}


// 保存数据到chrome.storage
function savePrompts(callback) {
    chrome.storage.local.set({ [STORAGE_KEY]: prompts }, function () {
        if (callback) callback();
    });
}


// 初始化UI
function initUI() {
    // 检查是否已存在容器
    if (document.getElementById('prompt-manager')) return;

    // 创建主容器
    const container = document.createElement('div');
    container.id = 'prompt-manager';
    container.innerHTML = `
            <div class="pm-header">
                <h3>提示词管理</h3>
                <div class="pm-header-buttons">
                    <button class="pm-icon-btn" id="pm-export">
                        <span class="pm-icon">📥</span>
                    </button>
                    <button class="pm-icon-btn" id="pm-import">
                        <span class="pm-icon">📎</span>
                    </button>
                    <button class="pm-icon-btn" id="pm-minimize">
                        <span class="pm-icon">👁️</span>
                    </button>
                    <button class="pm-icon-btn" id="pm-add">
                        <span class="pm-icon">+</span>
                    </button>
                    <button class="pm-icon-btn" id="pm-delete-all">
                        <span class="pm-icon">🗑️</span>
                    </button>
                </div>
            </div>
            <div class="pm-list" id="pm-list"></div>
            <div class="pm-search-container">
                <input type="text" id="pm-search" placeholder="🔍 搜索提示词..." class="pm-input pm-search">
            </div>

            <div class="pm-modal" id="pm-modal">
                <div class="pm-modal-content">
                    <div class="pm-modal-header">
                        <h4>${currentEditIndex !== null ? '✏️ 编辑提示词' : '➕ 新建提示词'}</h4>
                        <button class="pm-icon-btn" id="pm-close">
                            <span class="pm-icon">×</span>
                        </button>
                    </div>
                    <div class="pm-modal-body">
                        <input type="text" id="pm-title" placeholder="请输入标题..." class="pm-input">
                        <textarea id="pm-content" placeholder="请输入提示词内容..." class="pm-textarea"></textarea>
                    </div>
                    <div class="pm-modal-footer">
                        <button class="pm-btn pm-primary" id="pm-save">💾 保存</button>
                        <button class="pm-btn" id="pm-cancel">❌ 取消</button>
                    </div>
                </div>
            </div>
            <input type="file" id="pm-import-file" style="display: none;" accept=".json">
        `;
    document.body.appendChild(container);

    // 焦点追踪逻辑
    document.addEventListener('focusin', (e) => {
        if (!container.contains(e.target)) {
            const target = e.target;
            if (target.matches('input, textarea, [contenteditable="true"]')) {
                lastFocusedElement = target;
            }
        }
    });

    // 绑定事件
    bindEvents();

    // 加载数据并渲染
    loadPrompts(() => {
        filterPrompts();
    });
}

// 绑定事件
function bindEvents() {
    // 编辑提示词
    window.editPrompt = function (index) {
        currentEditIndex = index;
        document.getElementById('pm-title').value = prompts[index].title;
        document.getElementById('pm-content').value = prompts[index].content;
        document.getElementById('pm-modal').classList.add('show');
    };

    // 删除提示词
    window.deletePrompt = function (index) {
        if (confirm('确定要删除这个提示词吗？')) {
            prompts.splice(index, 1);
            savePrompts(() => {
                filterPrompts();
            });
        }
    };

    // 添加新提示词
    document.getElementById('pm-add').addEventListener('click', () => {
        currentEditIndex = null;
        document.getElementById('pm-title').value = '';
        document.getElementById('pm-content').value = '';
        document.getElementById('pm-modal').classList.add('show');
    });

    // 清空所有提示词
    document.getElementById('pm-delete-all').addEventListener('click', () => {
        if (prompts.length === 0) {
            return;
        }

        if (confirm(`确定要删除所有 ${prompts.length} 个提示词吗？此操作不可恢复！`)) {
            prompts = [];
            filteredPrompts = [];
            savePrompts(() => {
                filterPrompts();
                // 显示成功提示
                showNotification('所有提示词已清空', 'success');
            });
        }
    });

    // 显示通知
    function showNotification(message, type = 'info') {
        const notification = document.createElement('div');
        notification.style.cssText = `
                position: fixed;
                top: 80px;
                right: 20px;
                background: ${type === 'success' ? '#10b981' : '#3b82f6'};
                color: white;
                padding: 12px 20px;
                border-radius: 8px;
                font-size: 14px;
                font-weight: 500;
                z-index: 10001;
                box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
                animation: slideInRight 0.3s ease-out;
            `;
        notification.textContent = message;
        document.body.appendChild(notification);

        setTimeout(() => {
            notification.style.animation = 'slideOutRight 0.3s ease-in';
            setTimeout(() => {
                document.body.removeChild(notification);
            }, 300);
        }, 2000);
    }

    // 添加通知动画样式
    const style = document.createElement('style');
    style.textContent = `
            @keyframes slideInRight {
                from {
                    opacity: 0;
                    transform: translateX(100px);
                }
                to {
                    opacity: 1;
                    transform: translateX(0);
                }
            }
            @keyframes slideOutRight {
                from {
                    opacity: 1;
                    transform: translateX(0);
                }
                to {
                    opacity: 0;
                    transform: translateX(100px);
                }
            }
        `;
    document.head.appendChild(style);

    // 关闭模态框
    document.getElementById('pm-close').addEventListener('click', () => {
        document.getElementById('pm-modal').classList.remove('show');
    });

    // 取消操作
    document.getElementById('pm-cancel').addEventListener('click', () => {
        document.getElementById('pm-modal').classList.remove('show');
    });

    // 点击模态框背景关闭
    document.getElementById('pm-modal').addEventListener('click', (e) => {
        if (e.target.id === 'pm-modal') {
            document.getElementById('pm-modal').classList.remove('show');
        }
    });

    // 保存提示词
    document.getElementById('pm-save').addEventListener('click', () => {
        const title = document.getElementById('pm-title').value.trim();
        const content = document.getElementById('pm-content').value.trim();

        if (!title || !content) {
            alert('标题和内容不能为空');
            return;
        }

        if (currentEditIndex !== null) {
            prompts[currentEditIndex] = { title, content };
        } else {
            prompts.push({ title, content });
        }

        savePrompts(() => {
            filterPrompts();
            document.getElementById('pm-modal').classList.remove('show');
            showNotification('提示词已保存', 'success');
        });
    });

    // 最小化功能
    document.getElementById('pm-minimize').addEventListener('click', (e) => {
        e.stopPropagation();
        isMinimized = !isMinimized;
        document.getElementById('prompt-manager').classList.toggle('minimized', isMinimized);
    });

    document.getElementById('prompt-manager').addEventListener('click', () => {
        if (isMinimized) {
            isMinimized = false;
            document.getElementById('prompt-manager').classList.remove('minimized');
        }
    });

    // 导出功能
    document.getElementById('pm-export').addEventListener('click', () => {
        const json = JSON.stringify(prompts);
        const blob = new Blob([json], { type: 'application/json' });
        const url = URL.createObjectURL(blob);
        const a = document.createElement('a');
        a.href = url;
        a.download = 'prompts.json';
        document.body.appendChild(a);
        a.click();
        document.body.removeChild(a);
        URL.revokeObjectURL(url);
    });

    // 导入功能
    document.getElementById('pm-import').addEventListener('click', () => {
        document.getElementById('pm-import-file').click();
    });

    document.getElementById('pm-import-file').addEventListener('change', (event) => {
        const file = event.target.files[0];
        if (file) {
            const reader = new FileReader();
            reader.onload = (e) => {
                try {
                    const json = JSON.parse(e.target.result);
                    if (Array.isArray(json)) {
                        prompts = json;
                        savePrompts(() => {
                            filterPrompts();
                            alert('导入成功');
                        });
                    } else {
                        alert('文件格式不正确，应为JSON数组');
                    }
                } catch (error) {
                    alert('文件解析失败：' + error);
                }
            };
            reader.readAsText(file);
        }
    });

    // 搜索功能
    const searchInput = document.getElementById('pm-search');
    searchInput.addEventListener('input', () => {
        filterPrompts(searchInput.value.trim());
    });
}

// 渲染列表
function renderList() {
    const list = document.getElementById('pm-list');
    list.innerHTML = '';

    filteredPrompts.forEach((item, index) => {
        const listItem = document.createElement('div');
        listItem.classList.add('pm-item');
        listItem.innerHTML = `
                <span class="pm-item-title">${item.title}</span>
                <div class="pm-item-actions">
                    <button class="pm-icon-btn" style="background: linear-gradient(135deg, #10b981, #059669); color: white;" title="编辑">
                        <span class="pm-icon">✎</span>
                    </button>
                    <button class="pm-icon-btn" style="background: linear-gradient(135deg, #ef4444, #dc2626); color: white;" title="删除">
                        <span class="pm-icon">✕</span>
                    </button>
                </div>
            `;

        const [editBtn, deleteBtn] = listItem.querySelectorAll('.pm-icon-btn');

        editBtn.addEventListener('mousedown', e => e.preventDefault());
        deleteBtn.addEventListener('mousedown', e => e.preventDefault());

        editBtn.addEventListener('click', (e) => {
            e.stopPropagation();
            editPrompt(prompts.indexOf(item));
        });

        deleteBtn.addEventListener('click', (e) => {
            e.stopPropagation();
            deletePrompt(prompts.indexOf(item));
        });

        listItem.addEventListener('mousedown', e => e.preventDefault());

        listItem.addEventListener('click', () => {
            if (lastFocusedElement) {
                pasteToFocusedElement(item.content);
            } else {
                alert('请先点击需要输入的位置');
            }
        });

        list.appendChild(listItem);
    });
}

// 粘贴到焦点元素
function pasteToFocusedElement(text) {
    if (!lastFocusedElement) return;

    try {
        lastFocusedElement.focus();

        if (lastFocusedElement.isContentEditable) {
            const selection = window.getSelection();
            const range = selection.getRangeAt(0);
            range.deleteContents();

            // 插入文本 + 换行（兼容不同浏览器）
            const textWithNewLine = text + '\n\n';
            const textNode = document.createTextNode(textWithNewLine);
            range.insertNode(textNode);

            // 移动光标到新行开头
            const newRange = document.createRange();
            newRange.setStart(textNode, textWithNewLine.length); // 定位到末尾
            newRange.collapse(true); // 折叠范围到光标位置

            selection.removeAllRanges();
            selection.addRange(newRange);
        } else {
            const elem = lastFocusedElement;
            const start = elem.selectionStart;

            // 在文本后添加换行符
            const textWithNewLine = text + '\n\n';
            elem.setRangeText(textWithNewLine, start, start, 'end');

            // 将光标设置到新行的开头
            elem.selectionStart = elem.selectionEnd = start + textWithNewLine.length;
        }

        const event = new Event('input', { bubbles: true });
        lastFocusedElement.dispatchEvent(event);
    } catch (error) {
        console.error('粘贴失败，使用剪贴板回退');
        GM_setClipboard(text);
        alert('已复制到剪贴板，请手动粘贴');
    }
}

// 过滤提示词
function filterPrompts(searchTerm = '') {
    if (searchTerm) {
        const lowerSearchTerm = searchTerm.toLowerCase();
        filteredPrompts = prompts.filter(item =>
            item.title.toLowerCase().includes(lowerSearchTerm) 
            // item.title.toLowerCase().includes(lowerSearchTerm) ||
            // item.content.toLowerCase().includes(lowerSearchTerm)
        );
    } else {
        filteredPrompts = [...prompts];
    }
    renderList();
}

// 初始化函数
function initialize() {
    if (document.readyState === 'complete' || document.readyState === 'interactive') {
        setTimeout(initUI, 100);
    } else {
        document.addEventListener('DOMContentLoaded', () => {
            setTimeout(initUI, 100);
        });
    }
}

// 启动初始化
initialize();